package com.deli.pagingsimple;

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.LoadState;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class MainActivity extends AppCompatActivity {
    RecyclerView rvList;
    SmartRefreshLayout refreshLayout;
    MainPagingAdapter adapter;
    MainViewModel viewModel;
    ProgressBar progressBar;
    boolean isRefresh = false;
    Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(App.instance).create(MainViewModel.class);
        viewModel.init();
        disposable = new CompositeDisposable();
        initView();
    }

    private void initView() {
        rvList = findViewById(R.id.rv_list);
        rvList.setItemAnimator(null);
        progressBar = findViewById(R.id.progress);
        refreshLayout = findViewById(R.id.refresh);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        rvList.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MainPagingAdapter(this);
        adapter.bindToRecyclerView(rvList);

        disposable = viewModel.pagingData
                .subscribe(pagingData -> {
                    adapter.submitData(getLifecycle(), pagingData);
                });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            isRefresh = true;
            adapter.refresh();
        });


        adapter.addLoadStateListener(combinedLoadStates -> {
            if (combinedLoadStates.getSource().getRefresh() instanceof LoadState.NotLoading) {
                refreshLayout.finishRefresh();
            }

            if (combinedLoadStates.getSource().getRefresh() instanceof LoadState.Loading && !isRefresh) {
                progressBar.setVisibility(View.VISIBLE);
            } else {
                progressBar.setVisibility(View.GONE);
            }
            return null;
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.dispose();
    }
}